/**
 *@html common.singlePopup
 *@description 通用单选弹出框js实现
 *
 *@since 2011-11-17
 */
Ccay.Module.define("Ccay.Component.SinglePopup",function(self,$S){
	/**
	 * 单选弹出框页面初始化
	 */
	var popupBean="",servicePath="";

	self.init=function(bean){
		
		$S("input.ccay-dialog-button.cancel").val($i18n("ccay.common.label.close"));
		
		//如果 servicePath 未传入值，则使用ajax属性中的 url
		if(!bean.servicePath){
			var currUrl = bean.ajax.url;
			bean.servicePath = currUrl.indexOf("/page") == -1 ? currUrl : currUrl.substring(0,currUrl.indexOf("/page")) + currUrl.substring(currUrl.indexOf("?"),currUrl.length);
		}
		
		popupBean=bean;
		servicePath=bean.servicePath;
		
		//如果实现了自定条件区域，则跳用其方法，否则通过列来生成搜索条件区域
		if( typeof(bean.condRender) === "function" ){
			$S("#popup_cond_div").html(bean.condRender());
			
			//控件初始化
			Ccay.UI.init("#popup_cond_div");
			
			var btnHtml =['<br><center><SPAN id=btn_popup_single class="ccay-button search default" ><A class="ccay-icon search"></A><LABEL>'+ $.i18n.prop("ccay.common.button.search") +'</LABEL></SPAN>'];
			btnHtml.push('<SPAN  class="ccay-button reset" onclick =$(this).parents("form").ccayReset() ><A class="ccay-icon reset"></A><LABEL>'+ $.i18n.prop("ccay.common.button.reset") +'</LABEL></SPAN></center>')
			$S("#popup_cond_div").append(btnHtml.join(""));
		}else if( bean.buttonIsCenter ){
			initConditionArea(bean.columns, bean.buttonIsCenter);
		}else{
			initConditionArea(bean.columns);
		}
		if( typeof(bean.initRender) === "function" ){
			bean.initRender($S("#popup_cond_div"), self, $S);
		};
		//将预置条件设置如查询表单中
		if (typeof popupBean.queryParam == "function"){
			$S("#popup_cond_div").jsonData(popupBean.queryParam());
		}else if(typeof popupBean.queryParam == "object"){
			$S("#popup_cond_div").jsonData(popupBean.queryParam);
		}
		
		if($.type(popupBean.selectedItems) == "array"){
			popupBean.selectedItems = popupBean.selectedItems[0];
		}
		
		popupBean.defaultParam && $S("#popup_cond_div").jsonData(popupBean.defaultParam);
		
		initLeftTable();
		
		if(bean.uniqueKey && Ccay.History.isSupport(bean) &&  popupBean.historyKey &&  Ccay.History.hasHistory({historyKey : getHistoryKey()})){
			var historyList = Ccay.History.getHistory(getHistoryKey())
			if(historyList.length){
				$("#ipopup_tab").prepend($("#ipopup_tab").find("div[tabid='ipopup_tab_history']"));
				$("#ipopup_tab").ccayTab();
				var tab_manager = $("#ipopup_tab").manager();
				$("#btn_popup_single").bind("click",function(){
					tab_manager.getSelectedItemId() != 'ipopup_tab_all' && tab_manager.selectItem('ipopup_tab_all');
				});
				initHistoryGrid();
				return;
			}
		} 
		$("#ipopup_tab").children().removeAttr("title");
	};
	
	function getHistoryKey(){
		return popupBean.historyKey || popupBean.servicePath
	}
	/**
	 * @description 初始化数据集合grid
	 */
	function initLeftTable(){
		var columns = [{columnType: 'select', multi: false,field : popupBean.uniqueKey}];
		
		$.each(popupBean.columns,function(){
			if(this.id){
				this.field = this.id;
				if(this.id.indexOf("\.")){
					this.field = this.id;
					this.displayField = "{0} ? {1} : ''".formatText(this.field.split("\.")[0], this.field); 
				}
			}
			if(!this.width){
				this.width = 110;
			}
			columns.push($.extend({},this));
		});
		//查询请求地址
		if(!popupBean.ajax){
			var array = servicePath.split('?');
			var serviceUrl = ( popupBean.openPage === false || popupBean.openPage == "false" ) ? servicePath : (array.length> 1 ? array[0]+"/page/{0}/{1}?"+array[1] : servicePath+"/page/{0}/{1}");
		}
		
		var options={
			customSetting:false,
			autoLoad: popupBean.autoLoad === false ? false : true, 
			showSeq: popupBean.showSeq === false ? false : true, 		
			showPager:(popupBean.showPager === false || popupBean.noPage === true || popupBean.noPage == "true" ) ? false : true, 
			columns: columns,
			fnDataBindComplete:function(){
				if(popupBean.uniqueKey && popupBean.selectedItems){
					var td = $("#leftGrid").find("td[valuefield='{0}'][val='{1}'].grid-select".formatText(popupBean.uniqueKey,popupBean.selectedItems)).parent().addClass("igrid-selected")
				}
			},
			height : 365,
			ajax :$.extend({url:serviceUrl},popupBean.ajax),
			
			fnBeforeRequest : function(op){
				var bool = $.isEmptyObject(op.ajax.data);
				if(bool && (popupBean.allowEmptyCondition===false)){
					Ccay.UI.showMessage("ccay.popup.label.inputtip","warn");
					if(op.Storage.dataset.length){
						$S("#leftGridPager").find("div.ccay-pager-text").addClass("hide");
						$S("#leftGridPager").find("div.ccay-pager-panel").removeClass("hide");
					}
					return false; 
				}
				
				if(op.ajax.oldData == op.ajax.data){
					return true;
				}
				
				//op.ajax.data 是否有值，是否要进行封装
				op.ajax.url = popupBean.ajax ? popupBean.ajax.url : serviceUrl;
				
				if(!bool && popupBean.paramToJsonStr){
					op.ajax.url += (op.ajax.url.indexOf("?") > 0 ? "&" : "?")+popupBean.paramToJsonStr+"={"+Ccay.Core._ajax.serialize(op.ajax.data)+"}";
					op.ajax.data = {};
				}
				
				if(popupBean.queryParam){
					//op.ajax.data = $.extend({},popupBean.queryParam, op.ajax.data);
					//修正queryParam不能使用函数返回参数。
					op.ajax.data = $.extend({},typeof popupBean.queryParam == "function"?popupBean.queryParam():popupBean.queryParam, op.ajax.data);
				}
				
				op.ajax.oldData = op.ajax.data;
			},
			operation:{
				search:{
					autoSearch : typeof popupBean.autoSearch == "boolean" ? popupBean.autoSearch : true,
					//查询条件区域id选择器
					panel:'#popupSearchForm',
					btn : "#btn_popup_single"
				}
			}
			,pagerOp:{
				mode:null,
				showLast: popupBean.showLast!==false,
				
				pageInf: {
					pageSize: popupBean.pageSize || Ccay.UI.Config.pager.defaultSize
				},
				pageSizes: popupBean.pageSizeList || Ccay.UI.Config.pager.pageSizes
			},
			fnSelected : function(selected,tr,record){ 
				if(selected){
					setTimeout(function(){
						self.onOk(record);
					},10);
				}
			}

		};
		var currLeftOptions = $.type(popupBean.leftTableOptions) == "object" ? popupBean.leftTableOptions : (popupBean.event && popupBean.event.left);
		$S("#leftGrid").igrid($.extend(options,currLeftOptions)).delegate("tr.grid-row","dblclick",function(){
			var data =  $S("#leftGrid").manager().getRowData($(this));
			self.onOk(data);
		})
		
	};
	
	function initHistoryGrid(){
		
		var columns = [{columnType: 'select', multi: false,field : popupBean.uniqueKey}];
		$.each(popupBean.columns,function(){
			if(this.id){
				this.field = this.id;
				if(this.id.indexOf("\.")){
					this.field = this.id;
					this.displayField = "{0} ? {1} : ''".formatText(this.field.split("\.")[0], this.field); 
				}
			}
			if(!this.width){
				this.width = 110;
			}
			columns.push($.extend({},this));
		});
	
		var options={
			customSetting:false,
			columns: columns,
			showPager:false,
			fnDataBindComplete:function(){
				if(popupBean.uniqueKey && popupBean.selectedItems){
					var td = $("#popupHistoryTable").find("td[valuefield='{0}'][val='{1}'].grid-select".formatText(popupBean.uniqueKey,popupBean.selectedItems)).parent().addClass("igrid-selected")
				}
			},
			height : 365,
			fnSelected : function(selected,tr,record){ 
				if(selected){
					self.onOk(record);
				}
			}
		};
		var currHistoryOptions = $.type(popupBean.historyTableOptions) == "object" ? popupBean.historyTableOptions : {};
		$S("#popupHistoryTable").igrid($.extend(options,currHistoryOptions)).delegate("tr.grid-row","dblclick",function(){
			var data =  $S("#popupHistoryTable").manager().getRowData($(this));
			self.onOk(data);
		})

		
		var historyList = Ccay.History.getHistory(getHistoryKey());
		var values =[];
		$.each(historyList,function(){
			if(Ccay.DataHelper.hasValue(this.value)){
				values.push(this.value);
			}
		})
		Ccay.doPost(servicePath, values,function(datas){ 
			//排序
			var sortDatas = [];
			$.each(values,function(){
				var value = this;
				$.each(datas,function(){
					if(Ccay.DataHelper.getObj(popupBean.uniqueKey, this) == value){
						sortDatas.push(this);
						return false;
					}
				});
			});
			var grid = $S("#popupHistoryTable").manager();
			var datas = grid.op.Storage.dataset = sortDatas;
			grid.reload();
		},function(){return true})
	}
	
	/**
	 *@description 点击确认按钮后执行
	 * 1 得到popupBean中指定的回调函数的引用。（如果得不到引用则终止该方法）
	 * 2 得到已选项目，此为js对象，通过回调函数的传参返回。
	 */
	self.onOk=function(record){
		
		if(Ccay.History.isSupport(popupBean) &&  popupBean.uniqueKey &&  popupBean.historyKey){
			Ccay.History.save(getHistoryKey(), Ccay.DataHelper.getObj(popupBean.uniqueKey, record));
		}
		if(record){
			popupBean.callback && popupBean.callback(record);
		}else{
			var datas= $S("#leftGrid").manager().getSelectedRecords();
			if(datas && datas.length>0){
				popupBean.callback && popupBean.callback(datas[0]);
			}
		}
		self.closeDialog();
	};
	

	/**
	 * @description 通过参数动态生成条件区域dom
	 * @param {object[]} columns 列参数定义
	 * 
	 */
	function initConditionArea(columns, buttonIsCenter){

		var hasSearchColumn=false;
		var length=columns.length,autoWidth=true;
		$.each(columns,function(index,column){
			if(column.isCondition){
				hasSearchColumn=true;
				$S("#popup_cond_div").append($i18n(column.header)+" ");
				$S("#popup_cond_div").append("<input type='text' style='width:120px' name='"+column.id+"' maxlength='100'/>&nbsp;");
			}
			if(column.hidden)
				length--;
			if(column.width){
				autoWidth=false;
			}
		});
		if(length<=3 && autoWidth){
			$.each(columns,function(){
				this.width=parseInt(400/length);
			});
		}
		if(hasSearchColumn && buttonIsCenter){
			var btnHtml =['<br><br><center><SPAN id=btn_popup_single class="ccay-button search default" ><A class="ccay-icon search"></A><LABEL>'+ $.i18n.prop("ccay.common.button.search") +'</LABEL></SPAN>'];
			btnHtml.push('<SPAN  class="ccay-button reset" onclick =$(this).parents("form").ccayReset() ><A class="ccay-icon reset"></A><LABEL>'+ $.i18n.prop("ccay.common.button.reset") +'</LABEL></SPAN></center>')
			$S("#popup_cond_div").append(btnHtml.join(""));
		}else if(hasSearchColumn){
			var btnHtml =['<SPAN id=btn_popup_single class="ccay-button search default" ><A class="ccay-icon search"></A><LABEL>'+ $.i18n.prop("ccay.common.button.search") +'</LABEL></SPAN>'];
			btnHtml.push('<SPAN  class="ccay-button reset" onclick =$(this).parents("form").ccayReset() ><A class="ccay-icon reset"></A><LABEL>'+ $.i18n.prop("ccay.common.button.reset") +'</LABEL></SPAN>')
			$S("#popup_cond_div").append(btnHtml.join(""));
		}
	
	};


});



